/*
 * @Description: 命令下拉按钮
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-04-08 13:33:45
 */
import { BaseCommand, useCommandManager } from '@amcax/base';
import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Space } from 'antd';
import { MenuItemType } from 'antd/es/menu/interface';
import i18n from 'i18next';
import { Icon } from 'nextcae-base';
import React, { useState } from 'react';
import CmdButton from './CmdButton';
import styles from './styles.module.scss';

interface IProps {
  cmds: BaseCommand[];
  showLabel?: boolean;
}

export default function CmdSplitButton({ cmds, showLabel = true }: IProps) {
  const { invokeCmd } = useCommandManager();
  const [selectedCmd, setSelectedCmd] = useState(cmds[0]);
  const [open, setOpen] = useState(false);

  const handleMenuItemClick = (info: any, index: number) => {
    info.domEvent.stopPropagation();
    const cmd = cmds[index];
    setSelectedCmd(cmd);
    setOpen(false);
    invokeCmd(cmd);
  };

  const menuItems: MenuItemType[] = cmds.map((cmd, index) => ({
    key: cmd.id,
    label: i18n.t(cmd.label),
    icon: (
      <Icon
        name={cmd.icon}
        size={20}
        style={{ fontSize: '24px' }}
      />
    ),
    style: { pointerEvents: 'auto' },
    onClick: (info) => handleMenuItemClick(info, index),
  }));

  return (
    <div className={styles['styled-split-button']}>
      <Space.Compact block>
        <CmdButton
          cmd={selectedCmd}
          showLabel={showLabel}
        />
        <Dropdown
          menu={{
            items: menuItems,
          }}
          placement='bottom'
          onOpenChange={setOpen}
          open={open}>
          <Button icon={<DownOutlined />} />
        </Dropdown>
      </Space.Compact>
    </div>
  );
}
